﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using Easy.DAL;
using Easy.Model;
using System.Data;

namespace Easy.BLL
{
    /// <summary>
    /// 系统用户相关类
    /// <remarks>
    /// Edit:xujie 2016/4/20
    /// </remarks>
    /// </summary>
    public class SystemUserManager
    {
        private SystemUserDAL SystemUserDal;
        public SystemUserManager()
        {
            SystemUserDal = new SystemUserDAL();
        }

        public string Login(string empno, string pwd)
        {
            
            SystemUserModel user = new SystemUserModel();

            DataTable dt = SystemUserDal.GetSystemUserByPwd(empno, System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5"));


            if (dt.Rows.Count > 0)
            {
                FormsAuthentication.SetAuthCookie(dt.Rows[0]["UserName"].ToString().ToUpper(), true);

                //string strUser = JsonConvert.SerializeObject(user);
                //// 设置Ticket信息
                //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "UserName", DateTime.Now, DateTime.Now.AddMinutes(1200), false, strUser);
                //// 加密验证票据
                //string strTicket = FormsAuthentication.Encrypt(ticket);

                //// 使用新userdata保存cookie
                //HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket);
                //cookie.Expires = ticket.Expiration;
                //HttpContext.Current.Response.SetCookie(cookie);

                return "";
            }
            else
            {
                return "用户名或密码错误";
            }

        }

        /// <summary>
        /// 登出功能
        /// </summary>
        /// <returns></returns>
        public void LogOut()
        {
            FormsAuthentication.SignOut();
        }

        public SystemUserModel GetSystemUser(Guid SystemUserId)
        {
            DataTable dt = SystemUserDal.GetSystemUserById(SystemUserId);
            return ConvertToModel(dt);
        }

        public SystemUserModel GetSystemUserByUserName(string username)
        {
            DataTable dt = SystemUserDal.GetSystemUserByUserName(username);
            return ConvertToModel(dt);
        }
        
        
        /// <summary>
        /// 将dt转化为SystemUserModel
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        private SystemUserModel ConvertToModel(DataTable dt)
        {
            SystemUserModel user = new SystemUserModel();
            
            if (dt.Rows.Count > 0)
	        {
                DataRow dr = dt.Rows[0];

                user.CreatedBy = Guid.Parse(dr["createdby"].ToString());
                user.CreatedOn = Convert.ToDateTime(dr["CreatedOn"]);
                user.ModifiedBy = Guid.Parse(dr["modifiedby"].ToString());
                user.ModifiedOn = Convert.ToDateTime(dr["modifiedon"].ToString());
                user.OwningUser = Guid.Parse(dr["owninguser"].ToString());
                user.OwningBusinessUnit = Guid.Parse(dr["owningbusinessunit"].ToString());
                user.BusinessUnitId = Guid.Parse(dr["BusinessUnitId"].ToString());
                user.UserName = dr["UserName"].ToString();
                if (!(dr["Sex"] is DBNull))
                    user.Sex = Convert.ToInt32(dr["Sex"]);
                user.UserImg = dr["UserImg"].ToString();
                user.Email = dr["Email"].ToString();
                user.Password = dr["Password"].ToString();

                user.Name = dr["Name"].ToString();

                user.SystemUserId = new Guid(dr["SystemUserId"].ToString());
	        }
            

            return user;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public string Updatepass(Guid id, string oldpass, string newpass)
        {
            string message="";
            SystemUserDAL user = new SystemUserDAL();
            DataTable dt = user.GetSystemUserById(id);
            if (dt.Rows.Count == 0) return "原密码错误";
            string npass = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(newpass, "MD5");
            string opass=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(oldpass, "MD5");
            string pass = dt.Rows[0]["Password"] == null ? "" : dt.Rows[0]["Password"].ToString();
            string tlmgh = dt.Rows[0]["UserName"] == null ? "" : dt.Rows[0]["UserName"].ToString();
            if (pass == opass)
            {
                int i = user.Updatesystemuserpass(id, npass);
               if (i>0)
               {
                   message = "密码修改成功";
               }
               else
               {
                   message = "密码修改失败";
               }
            }
            else
            {
                message = "原密码错误";
            }
            return message;
        }
    }
}
